<?php
namespace app\http\middleware;
use think\facade\Session;
use think\facade\Cookie;
use think\Loader;
use app\common\library\Token;
use app\common\model\MemberLogin;

class Auth
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 判断权限
     */
    public function handle($request, \Closure $next){
        //权限配置
        $this->noNeedLogin['index'] = ['index', 'login'];
        $this->noNeedLogin['member'] = ['login', 'register', 'third'];
        $this->noNeedLogin['api'] = ['*'];

        $this->noNeedRight['index'] = ['index', 'login'];
        $this->noNeedRight['member'] = ['login', 'register', 'third'];
        $this->noNeedRight['api'] = ['*'];

        $request->filter('trim,strip_tags,htmlspecialchars');
        $modulename = $request->module();
        $request->_modulename = $modulename;
        $controllername = Loader::parseName($request->controller());
        $request->_controllername = $controllername;
        $actionname = strtolower($request->action());
        $request->_actionname = $actionname;

        // token
        $token = $request->server('HTTP_TOKEN', $request->request('token', Cookie::get('token')));
        $requestUri = str_replace('.', '/', $controllername) . '/' . $actionname;
        $request->_logined = true; //登录判断初始化
        $request->_righted = true; //权限判断初始化
        $request->_interfaced = true; //接口判断初始化

        //echo $modulename.'/'.$requestUri;exit;

        if (!$this->match($actionname,$this->noNeedLogin[$modulename])){
            //如果必须登录，那么就判断是否登录
            $data = Token::get($token);
            if (!$data) {
                $request->_logined = false;
            }else{
                $memberid = intval($data['memberid']);
                if ($memberid > 0) {
                    $user = MemberLogin::get($memberid);
                    if (!$user) {
                        $request->_errormessage = '账号不存在';//setError('Account not exist');
                        $request->_logined = false;
                    }
                    if ($user['status'] != 'normal') {
                        $request->_errormessage = '账号已经被锁定';
                        $request->_logined = false;
                    }
                    $request->_member = $user;
                    $request->_logined = true;
                    $request->_token = $token;

                    //初始化成功的事件
                    //Hook::listen("user_init_successed", $this->_user);
                    $request->_logined = true;
                    //判断权限--判断是否需要验证权限
                    if (!$this->match($actionname,$this->noNeedRight[$modulename])){
                        //得到当前会员的角色
                        $groupid = $user->membergroup->itemid;
                        //得到当前会员角色的权限
                        $rules = explode(',', $user->membergroup->rules);
                        $wherearry = array();
                        $wherearry['status'] = array('eq',1);
                        $wherearry['itemid'] = array('in',$rules);
                        $rulelist = array();
                        if(Session::has('__rulelist__')){
                            $rulelist = Session::get('__rulelist__');
                        }else{
                            $rulelist = model('MemberRule')->where($wherearry)->select();
                            Session::set('__rulelist__',$rulelist);
                        }                        
                        $rules2 = [];
                        foreach ($ruleList as $k => $v){
                            $rules2[] = $v['title'];
                        }
                        $url = strtolower($modulename.'/'.$requestUri);
                        if(!in_array($url, $rules2)){
                            $request->_righted = false;
                        }
                        //判断接口权限
                        $interfaces = explode(',',$user->membergroup->interfaces);
                        if(!in_array('app/'.$url, $rules2)){
                            $request->_interfaced = false;
                        }
                        // $this->rules = UserRule::where('status', 'normal')->where('id', 'in', $rules)->field('id,pid,name,title,ismenu')->select();
                        // 判断控制器和方法判断是否有对应权限
                        // if (!$this->auth->check($path)) {
                        //     $this->error(__('You have no permission'));
                        // }
                    }
                } else {
                    $request->_errormessage = '账号还未登录';
                    //$this->setError('You are not logged in');
                    $request->_logined = false;
                }
            }            
        }else{
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $data = Token::get($token);
                if (!$data) {
                    $request->_logined = false;
                }
            }
            //$request->controller->error('Please login first');
            //$this->error(__('Please login first'), 'member/member/login');
        }
        //print_r($_SERVER['HTTP_USER_AGENT']);exit;
        //print_r(request()->module());
        //print_r($_SERVER['REQUEST_TIME']);exit;
        $request->_istouch = $this->is_touch();//判断客户端是移动还是PC
        $this->init();
        return $next($request);
    }
    public function is_touch(){
        return preg_match("/(iPhone|iPad|iPod|Android)/i", $_SERVER['HTTP_USER_AGENT']) ? 1 : 0;
    }
    public function init(){        
        // print_r($this->noNeedLogin);
        // exit;
    }

    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($actionname = '',$arr = [])
    {
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array($actionname, $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }
}
